<template>
	<view class="main-container">
		<!-- 类别分段器 -->
		<u-subsection :list="subsectionList" bgColor="#dedede" active-color="#ff5a00" inactive-color="#666" mode="button"
			:current="current" @change="sectionChange"></u-subsection>
		<!-- 兑换view -->
		<view class="exchange-code" v-if="current === 0">
			<uni-title type="h3" title="输入所持本品牌蟹卡兑换码开始兑换"></uni-title>
			<uni-easyinput class="exchange-input" trim="all" v-model="cardCode" placeholder="请输入兑换码"></uni-easyinput>
			<u-button :disabled="cardCode === ''" class="confirm-btn" text="兑换" @click="exchangeConfirm"
				color="radial-gradient(circle, #f00, #ff975e)"></u-button>

			<!-- 选择地址 -->
			<u-modal :show="modalShow" :title="modalTitle" showCancelButton @cancel="modalShow = false"
				@confirm="modalConfirm">
				<scroll-view scroll-y class="slot-content exchange-address-modal">
					<uni-search-bar placeholder="输入姓名或电话进行搜索" bg-color="#efefef" @confirm="searchEvent" />
					<!-- 地址list -->
					<view class="address-list">
						<!-- item -->
						<view class="address-item" :class="activeIndex === index ? 'active' : ''"
							v-for="(item, index) in addressList" :key="item.id" @click="selectThisAddress(index, item.id)">
							<uni-list-item :border="false" title="收货人" :note="item.name" />
							<uni-list-item :border="false" title="联系电话" :note="item.phone" />
							<uni-list-item :border="false" title="收货地址" :note="item.city + item.detail" />
							<!-- 已被选择标识 -->
							<view class="top-right-icon" v-if="activeIndex === index">
								<uni-icons type="checkmarkempty" color="#fff" size="16"></uni-icons>
							</view>
						</view>
					</view>
				</scroll-view>
			</u-modal>

			<view class="exchange-rules" @click="readRules">兑换说明</view>
			<u-popup :show="rulesShow" @close="rulesClose" closeable>
				<view class="rules-list">
					<uni-section title="兑换方式" sub-title="输入蟹卡背面兑换码,点击'兑换'按钮" type="line"></uni-section>
					<uni-section title="兑换次数" sub-title="每张蟹卡,仅限兑换一次" type="line"></uni-section>
					<uni-section title="蟹卡有效期" sub-title="蟹卡购买后(以到货时间为准),2年内可随时兑换" type="line"></uni-section>
					<uni-section title="蟹卡说明" sub-title="兑换码刮开后,蟹卡不支持退换;蟹卡是一次性全部兑付的礼品卡" type="line"></uni-section>
					<uni-section title="客服电话" sub-title="13812345678" type="line"></uni-section>
				</view>
			</u-popup>
		</view>
		<!-- 记录view -->
		<mescroll-body v-else ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption"
			:bottom="50">
			<uni-card v-for="(item, index) in list" :key="item.id" margin="0">
				<view slot="title" class="card-title">
					<view>
						<uni-section :title="'蟹卡编号：' + item.code">
							<template v-slot:right>
								<view class="tag-view">
									<uni-tag inverted :text="item.statusName" :type="item.statusType" />
								</view>
							</template>
						</uni-section>
					</view>
				</view>
				<view class="card-body">
					<view class="goods-list">
						<!-- <uni-list-item :border="false" title="商品型号" :note="尊享型蟹卡" />
						<uni-list-item :border="false" title="商品规格" note="母2.0两/4只(90g-105g) | 公2.5两/4只(115g-130g)" /> -->
						<uni-list-item :border="false" title="收货人" :note="item.clientName + ' ' + item.clientPhone" />
						<uni-list-item :border="false" title="收货地址" :note="item.clientCity + item.clientDetail" />
						<uni-list-item v-if="item.send_code" :border="false" title="物流单号" :note="item.send_code">
							<view slot="footer">
								<uni-tag text="复制物流号码" type="primary" inverted @click="copySendCode(item.send_code)" />
							</view>
						</uni-list-item>
					</view>
				</view>
				<view slot="actions" class="cart-footer">
					<view class="date">
						兑换时间：{{item.ent_date.substring(0, 10)}}
					</view>
				</view>
			</uni-card>
		</mescroll-body>
	</view>
</template>

<script>
	import {
		getExchangeList,
		addExchange
	} from "@/utils/wx_exchange.js"
	import {
		getAddressList
	} from "@/utils/wx_address.js"
	// 引入mescroll-mixins.js
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				modalShow: false,
				modalTitle: "选择地址",
				keywords: "",
				activeIndex: null,
				subsectionList: ['兑换', '记录'],
				current: 0,
				cardCode: "",
				rulesShow: false,
				list: [],
				addressList: [],
				activeAddressId: "",
				upOption: {
					noMoreSize: 5,
					textNoMore: "-- 没有更多 --",
					toTop: {
						offset: 200
					}
				}
			}
		},
		methods: {
			copySendCode(code) {
				uni.setClipboardData({
					data: code,
					success: () => {
						uni.showToast({
							title: "复制成功",
							icon: "success"
						})
					}
				})
			},
			async modalConfirm() {
				try {
					if (!this.activeAddressId) {
						uni.showToast({
							title: "请选择地址",
							icon: "error"
						})
					} else {
						let res = await addExchange({
							openid: uni.getStorageSync('openid'),
							code: this.cardCode,
							address_id: this.activeAddressId
						})
						uni.showToast({
							title: "已提交兑换申请",
							icon: "success",
							duration: 2000,
							success: () => {
								this.modalShow = false;
								this.cardCode = ""
							}
						})
					}
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			selectThisAddress(index, id) {
				this.activeIndex = index;
				this.activeAddressId = id
			},
			searchEvent(e) {
				this.keywords = e;
			},
			sectionChange(index) {
				this.current = index
			},
			async getMyAddressData() {
				try {
					let res = await getAddressList({
						openid: uni.getStorageSync('openid'),
						pageSize: -1
					})
					// console.log(res)
					this.addressList = res.data.rows
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			async exchangeConfirm() {
				try {
					// 如果兑换码有固定格式，可以先本地校验
					// if (this.cardCode !== "123") {
					// 	uni.showToast({
					// 		icon: "error",
					// 		title: "兑换码有误！"
					// 	})
					// }
					// 请求后端校验是否已被使用
					let res = await getExchangeList({
						keywords: this.cardCode
					})
					// console.log(res)					
					if (res.data.total > 0) {
						uni.showToast({
							icon: "error",
							title: "兑换码已使用！"
						})
						return;
					} else {
						uni.showModal({
							title: "提示",
							content: "兑换码校验成功，确定要兑换吗？",
							success: (res) => {
								if (res.confirm) {
									this.getMyAddressData()
									this.modalShow = true
								} else {
									console.log('取消兑换')
								}
							}
						})
					}
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			readRules() {
				this.rulesShow = true
			},
			rulesClose() {
				this.rulesShow = false
			},
			/*上拉加载的回调*/
			refreshList() {
				this.mescroll.resetUpScroll();

			},
			upCallback(page) {
				// console.log("upcallback")
				this.getMyList(page)
			},
			async getMyList(page) {
				try {
					let res = await getExchangeList({
						params: JSON.stringify({
							pageSize: page.size,
							currentPage: page.num,
							openid: uni.getStorageSync('openid')
						})
					});
					console.log(res);
					let curPageData = res.data.rows;
					let curPageLen = curPageData.length;
					let totalSize = res.data.total;
					let totalPage = Math.ceil(totalSize / page.size);
					let hasNext = true
					if (res.data.rows.length < page.size) {
						hasNext = false
					} else {
						hasNext = true
					}
					if (page.num == 1) {
						this.list = []
					}
					this.list = this.list.concat(curPageData)
					this.mescroll.endByPage(curPageLen, totalPage);
				} catch (err) {
					console.log(err, '获取项目列表失败');
					this.mescroll.endErr()
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.main-container {
		min-height: 100vh;
		padding: 3vw;
		box-sizing: border-box;
		background-color: #f7f7f7;
	}

	/deep/.exchange-code {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10vw;

		.uni-easyinput {
			margin: 5vw 0 15vw 0;
		}

		.u-button {
			border-radius: 50%;
			width: 40vw;
			height: 40vw;
			line-height: 40vw;
			text-align: center;
			font-weight: bold;
			color: #fff;

			.u-button__text {
				font-size: 40rpx !important;
			}
		}

		.u-button--disabled {
			background: #d6d6d6 !important;
			opacity: 1 !important;

			.u-button__text {
				color: #b2b2b2 !important;
			}
		}

		.exchange-rules {
			position: fixed;
			bottom: 100rpx;
			font-size: 30rpx;
			color: #ff5a00;
			line-height: 50rpx;
			height: 50rpx;
			width: 200rpx;
			border: 1px solid #ff5a00;
			text-align: center;
			border-radius: 10rpx;
		}
	}

	/deep/.uni-card {
		margin-top: 30rpx !important;

		.card-title {
			border-bottom: 1px solid #eee;
		}

		.card-body {
			.uni-list-item__container {
				padding: 10rpx 0 !important;
			}
		}

		.cart-footer {
			padding: 0 16rpx 16rpx 16rpx;
			color: #999;
			text-align: right;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.date {
				width: 100%;
			}
		}
	}

	// 选择地址弹窗
	/deep/ .exchange-address-modal {
		width: 100%;
		max-height: 75vh;

		.uni-searchbar {
			padding: 20rpx 0 !important;
		}

		.address-item {
			border: 1px solid #efefef;
			padding: 20rpx;
			box-sizing: border-box;
			position: relative;
			margin-bottom: 20rpx;

			.uni-list-item__container {
				padding: 10rpx 0 !important;
			}

			&.active {
				border: 1px solid #ff5a00;
			}

			.top-right-icon {
				width: 40rpx;
				height: 40rpx;
				position: absolute;
				right: 0;
				top: 0;
				background-color: #ff5a00;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>